#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>

DIR *dp;
struct dirent *dirp;
struct stat buf;

int AendisB(const char *a, const char *b);

int main(int argc, const char *argv[])
{
	char newfile[70];
	char tempfiledir[70];
	char shell[128];
	int result;
	long newtime = 0;

	dp = opendir("./");//打开当前目录
	while((dirp = readdir(dp)) != NULL)
	{
		if(strcmp(dirp->d_name, ".")==0 || strcmp(dirp->d_name,"..")==0)//忽略隐藏文件
		{
			continue;
		}
		if(AendisB(dirp->d_name, ".c") == 0)//文件名不是.c后缀则跳过本次循环
		{
			continue;
		}

		strcpy(tempfiledir, "./");
		strcat(tempfiledir, dirp->d_name);
		result = stat(tempfiledir, &buf);
		if(result != 0)
		{
			perror(" 访问文件状态信息出错");
		}
		else if(buf.st_mode & S_IFMT != S_IFREG)//不是普通文件跳过本次循环
		{
				continue;
		}
		{
			if(newtime < buf.st_ctime)
			{
				newtime = buf.st_ctime;
				strcpy(newfile, dirp->d_name);
			}
		}
	}

	//printf("最新的.c文件是: %s\n", newfile );
	closedir(dp);

	strcpy(shell, "gcc ");
	strcat(shell, newfile);

	system("clear");
	system("rm a.out");
	system(shell);
	printf("已尝试编译[%s]并运行\n", newfile);
	system("./a.out");

	return 0;
}

int AendisB(const char *a, const char *b)//A字符串以B字符串结尾返回1，否则返回0
{
	return (strstr(a, b) != NULL && strstr(a, b) == a + strlen(a) - strlen(b));
}

